<template lang="pug">
Dialog(
  title="提示"
  v-model="dialogVisible"
  hide-cancel
  hide-close
)
  p 以下人员存在可合管的项目，是否合管
  Form(
    v-bind="formProps"
  )
</template>

<script setup lang="ts">
import type { SpecimenEntity } from "@scmt/api-lis-specimen";
import { Dialog, Form, type FormProps } from "@scmt/common-components";

type EditModel = Record<string, SpecimenEntity[]>;
type EditObj = Record<string, 0 | 1>;

const props = defineProps({
  model: {
    type: Object as PropType<null | EditModel>,
    default: () => null,
  },
});

const emits = defineEmits<{
  saved: [EditObj];
}>();

const { model } = toRefs(props);

const editingObj = ref<EditObj>(createEditingObj(model.value));

const items = computed<FormProps["items"]>(() => {
  if (!model.value) {
    return [];
  }

  return Object.keys(model.value).map((key) => {
    const patientName = model.value![key][0].patientName;
    const label = model.value![key].map((i) => i.applicationProject).join("、");
    return {
      label: patientName,
      prop: key,
      as: "checkbox",
      options: {
        trueValue: 1,
        falseValue: 0,
        label,
      },
    };
  });
});

const formProps = computed(() => {
  const props: FormProps = {
    model: editingObj.value,
    items: items.value,
    columns: 1,
  };

  return props;
});

const dialogVisible = computed({
  get() {
    return Boolean(props.model);
  },
  set(val) {
    !val && emits("saved", editingObj.value);
  },
});

watch(dialogVisible, (val) => {
  if (val) {
    editingObj.value = createEditingObj(model.value);
  }
});

function createEditingObj(model?: EditModel | null): EditObj {
  return Object.keys(model || {}).reduce(
    (acc, cur) => ({ ...acc, [cur]: 1 }),
    {} as EditObj
  );
}
</script>

<style lang="less" scoped></style>
